import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:study_flutter/yzhg/dartTools/YEventBusUtil.dart';
import 'package:study_flutter/yzhg/project/shop/content/Content.dart';
import 'package:study_flutter/yzhg/project/shop/event/YEventBusBean.dart';

import 'CardInfoBean.dart';
import 'SuccessBack.dart';

class CartProvide with ChangeNotifier {
  String cartString = "[]";

  List<CardInfoBean> cardInfoBean;

  /*保存数据的方法*/
  save(goodsId, goodsName, count, price, images) async {
    //初始化sp
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo'); //获取持久化存储的值
    print("获取到的数据${cartString}");
    //判空
    var temp = (cartString == null) ? [] : json.decode(cartString.toString());

    List<Map> tempList = (temp as List).cast();
    //判断购物车中是否存在此商品
    var isHave = false;
    //标记索引
    int ival = 0;
    tempList.forEach((element) {
      if (element["goodsId"] == goodsId) {
        tempList[ival]["count"] = element['count'] + 1;
        cardInfoBean[ival].count++;
        isHave = true;
      }
      ival++;
    });
    //  如果没有，进行增加
    if (!isHave) {
      Map<String, dynamic> newGoods = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images
      };
      tempList.add(newGoods);
      cardInfoBean.add(new CardInfoBean.fromJson(newGoods));
    }
    //把字符串进行encode操作，
    cartString = json.encode(tempList).toString();
    print(cartString);
    print(cardInfoBean.toString());
    prefs.setString('cartInfo', cartString); //进行持久化
    notifyListeners();
  }

  /*清除数据*/
  remove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //prefs.clear();//清空键值对
    prefs.remove('cartInfo');
    print('清空完成-----------------');
    notifyListeners();
  }

  /*删除某一条数据*/
  deleteGoods(goodsId, SuccessBack successBack) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo'); //获取持久化存储的值
    print("获取到的数据${cartString}");
    //判空
    var temp = (cartString == null) ? [] : json.decode(cartString.toString());
    //转化为集合对象
    List<Map> tempList = (temp as List).cast();
    var goodsMap;
    //遍历查找
    //for循环索引
    for (var i = 0; i < tempList.length; i++) {
      if (tempList[i]["goodsId"] == goodsId) {
        //找到这个商品
        print("=====================找到这个商品");
        goodsMap = tempList[i];
        break;
      }
    }

    //判断是否查询到这个商品
    if (goodsMap != null) {
      //有这个商品
      tempList.remove(goodsMap);
      //把字符串进行encode操作，
      cartString = json.encode(tempList).toString();
      prefs.setString('cartInfo', cartString); //进行持久化
      successBack.onSuccess("SUCCESS"); //回调
      notifyListeners();
    } else {
      successBack.onError("Ex");
    }
  }


  /*加减号操作*/
  subtractAdd(goodsId,isAdd) async{
    //初始化sp
    SharedPreferences prefs = await SharedPreferences.getInstance();
    cartString = prefs.getString('cartInfo'); //获取持久化存储的值
    print("获取到的数据${cartString}");
    //判空
    var temp = (cartString == null) ? [] : json.decode(cartString.toString());

    List<Map> tempList = (temp as List).cast();
    //标记索引
    int ival = 0;
    tempList.forEach((element) {
      if (element["goodsId"] == goodsId) {
        if(isAdd){
          tempList[ival]["count"] = element['count'] + 1;
          cardInfoBean[ival].count++;
        } else {
           if(tempList[ival]["count"] > 1){
             tempList[ival]["count"] = element['count'] - 1;
             cardInfoBean[ival].count--;
           }
        }
      }
      ival++;
    });
    //把字符串进行encode操作，
    cartString = json.encode(tempList).toString();
    print(cartString);
    print(cardInfoBean.toString());
    prefs.setString('cartInfo', cartString); //进行持久化
    YEventBusUtil.getInstance().fire(YEventBusBean(Content.EVENT_CART_CNAHGE,eventBool: true));
  }

  /*获取购物车的商品*/
  getCartInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();

    //获取  保存的数据
    cartString = prefs.getString("cartInfo");
    cardInfoBean = [];
    //判空
    if (cartString == null) {
      cardInfoBean = [];
    } else {
      List<Map> tempList = (json.decode(cartString.toString()) as List).cast();
      tempList.forEach((element) {
        cardInfoBean.add(new CardInfoBean.fromJson(element));
      });
    }
    print(cardInfoBean.length);
    notifyListeners();
  }
}
